package OOPAndMultiThreadArchiveManager.Client.Views;

import OOPAndMultiThreadArchiveManager.Client.Controllers.HttpController;
import OOPAndMultiThreadArchiveManager.Client.Models.ApiReceive;
import OOPAndMultiThreadArchiveManager.Client.Models.ApiResponse;
import OOPAndMultiThreadArchiveManager.Client.Models.UserInfo;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.swing.*;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;

public class UserInfoManageView {
    private JTabbedPane tabbedPane2;
    private JPasswordField passwordField1;
    private JPasswordField passwordField2;
    private JButton changePasswordButton;
    private JPanel changePasswordPanel;
    private JPanel JPanel3;
    private JFrame frame;
    private UserInfo userInfo;
    private ObjectMapper objectMapper = new ObjectMapper();

    public UserInfoManageView(UserInfo userInfo) {
        this.userInfo = userInfo;

        changePasswordButton.addActionListener(e -> changePasswordAsync());

        frame = new JFrame("UserInfoManageView");
        frame.setContentPane(JPanel3);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.pack();
        frame.setSize(600, 360);
        frame.setLocationRelativeTo(JPanel3);
        frame.setVisible(true);
    }

    private void changePasswordAsync() {
        var password1 = String.valueOf(passwordField1.getPassword());
        var password2 = String.valueOf(passwordField2.getPassword());
        if (!password1.equals(password2)) {
            JOptionPane.showMessageDialog(frame, "两次输入的密码不同，请重新输入。");
            return;
        }
        if (!Pattern.compile("^[a-zA-Z\\d._]{1,128}$").matcher(password1).matches()) {
            JOptionPane.showMessageDialog(frame, "非法的密码");
            return;
        }
        var request = new ApiReceive();
        request.api = ApiReceive.Api.PUT_User$Password;
        request.user.name = userInfo.user;
        request.user.password = userInfo.password;
        request.data = password1;
        CompletableFuture.supplyAsync(() -> new HttpController().Request(request))
                .whenCompleteAsync(((response, throwable) -> {
                    if (response.apiCode == ApiResponse.ApiCode.Success) {
                        JOptionPane.showMessageDialog(frame, "修改密码成功，请重新登录。");
                    } else if (response.apiCode == ApiResponse.ApiCode.Unauthorized) {
                        JOptionPane.showMessageDialog(frame, "验证失败，请检查你的账号和密码。");
                    } else if (response.apiCode == ApiResponse.ApiCode.Failed) {
                        JOptionPane.showMessageDialog(frame, objectMapper.convertValue(response.data, String.class));
                    }
                }));
    }
}
